import { computed, defineComponent, nextTick, onMounted, ref } from 'vue'
import ReTable from '@/components/table'
import ReForm, { type EasyFormInstance } from '@/components/form'
import props from './props'
import './index.scss'
import { ElButton, ElCol, ElFormItem } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { isObject } from '@/store/util'

const defaultPagination = {
  pageSize: 10,
  currentPage: 1,
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [10, 20, 50, 100],
  background: true,
  total: 0,
  align: 'right'
}

const defaultSearchLayout = {
  span: 6,
  gutter: 20
}

export default defineComponent({
  name: 'ReProTable',
  props,
  setup(props, { attrs, emit }) {
    const { t } = useI18n()
    console.log('ReProTable props', attrs)

    const searchLayout = props.options?.searchLayout || {}
    const mergeSearchLayout = computed(() =>
      Object.assign(defaultSearchLayout, searchLayout)
    )

    const mergePagination = computed(() => {
      if (props.pagination?.currentPage) {
        return Object.assign(defaultPagination, props.pagination)
      }
      return null
    })

    const fieldList = computed(() => {
      return props.columns.filter(item => (item as { search: boolean })?.search)
    })

    /** search表单部分的逻辑 */
    const isExpand = ref(false)
    const btnRef = ref()
    const searchRef = ref()
    const showIndex = ref(0)
    /**
     * 检查搜索布局是否溢出，并计算显示索引
     *
     * 该函数用于检测搜索区域的宽度是否足够显示所有按钮，
     * 如果溢出则调整显示索引以适应布局
     */
    const checkOverflow = () => {
      nextTick(() => {
        // 如果搜索布局跨度大于12，则直接设置显示索引为1
        if (mergeSearchLayout.value.span > 12) {
          return (showIndex.value = 1)
        }

        // 获取搜索区域和按钮的宽度，计算可显示的按钮数量
        const searchWidth = getElBoxProperty(searchRef.value, 'width')
        const btnWidth = Math.max(
          getElBoxProperty(btnRef.value.$el, 'width'),
          270
        )
        showIndex.value = Math.floor(searchWidth / btnWidth) - 1
      })
    }
    const overflow = computed(() => {
      if (fieldList.value.length > 0) {
        return fieldList.value.length > showIndex.value
      }
      return false
    })

    const showFileds = computed(() => {
      if (isExpand.value) return fieldList.value
      return fieldList.value.slice(
        0,
        Math.min(showIndex.value, fieldList.value.length)
      )
    })

    /** 获取dom元素占据空间属性 */
    const getElBoxProperty = (el: any, property: string) => {
      return parseInt(el.getBoundingClientRect()[property])
    }
    onMounted(() => {
      checkOverflow()
    })

    const changeExpand = () => {
      isExpand.value = !isExpand.value
    }

    const onSearch = () => emit('search', props.searchForm)
    const formRef = ref<EasyFormInstance>(null)
    const onReset = () => {
      formRef.value?.formRef?.resetFields()
      emit('reset', props.searchForm)
    }
    /** ---------------------------- */

    /** 渲染 搜索区域的dom 待优化【props一些类似size的绑定】*/
    const renderSearchButton = () => {
      return (
        <ElCol
          span={
            mergeSearchLayout.value.span
              ? Math.min(
                  mergeSearchLayout.value.span,
                  12,
                  24 - mergeSearchLayout.value.span
                )
              : null
          }
          ref={btnRef}
        >
          <ElFormItem>
            <ElButton type="primary" onClick={onSearch}>
              {props.options?.searchBtnText ?? t('button.queryText')}
            </ElButton>
            <ElButton onClick={onReset}>
              {props.options?.resetBtnText ?? t('button.resetText')}
            </ElButton>
            {overflow.value && (
              <ElButton text onClick={changeExpand}>
                {isExpand.value
                  ? t('button.shrinkText')
                  : t('button.expandText')}
              </ElButton>
            )}
          </ElFormItem>
        </ElCol>
      )
    }

    const defaultToolbar = {
      title: '标题'
    }
    const mergeToolbar = computed(() => {
      if (props.toolbar && isObject(props.toolbar)) {
        return Object.assign(defaultToolbar, props.toolbar)
      }
      return defaultToolbar
    })
    const renderToolbar = () => {
      return (
        <div className="easy-pro-table-toolbar">
          {mergeToolbar.value.title && <div>{mergeToolbar.value.title}</div>}
        </div>
      )
    }

    const renderProTableLayout = () => {
      return (
        <div className="easy-pro-table">
          {fieldList.value.length > 0 && (
            <div className="easy-pro-table-search" ref={searchRef}>
              <ReForm
                ref={formRef}
                formData={props.searchForm}
                fieldList={showFileds.value}
                {...props.options}
                {...mergeSearchLayout.value}
              >
                {renderSearchButton()}
              </ReForm>
            </div>
          )}
          {props.toolbar && renderToolbar()}
          <div className="easy-pro-table-content">
            <ReTable
              data={props.data}
              columns={props.columns}
              pagination={mergePagination.value}
            />
          </div>
        </div>
      )
    }
    return () => renderProTableLayout()
  }
})
